const path = require('path');
const fs = require("fs");
const ffmpeg = require('fluent-ffmpeg');
/**
 * use全局参数
 * agreement 协议头
 */
/*上传视频*/
const upload_file_video = (req, res) => {
	let obj_file = {
		code: -1,
		path: "",
		type: "",
		msg: "上传失败"
	};
	try {
		res.header("Access-Control-Allow-Origin", "*");
		let file = req.file || 'null';
		let filetype = (req.file && req.file.mimetype) || 'null';
		obj_file.type = filetype

		if (file === 'null') {
			obj_file.msg = "请上传文件";
			res.end(JSON.stringify(obj_file));
			return;
		}
		const {
			originalname,
			filename,
			mimetype,
			size
		} = file;
		let newFilePath, newThumbnailPath;
		let newfilename = `vt_${path.basename(filename, path.extname(filename))}.webp`
		if (isProd) {
			newFilePath = `${agreement}://${req.hostname}/videos/${filename}`;
			newThumbnailPath = `${agreement}://${req.hostname}/videos_thumbnail/${newfilename}`;
		} else {
			newFilePath = `${agreement}://${req.hostname}:${port}/videos/${filename}`;
			newThumbnailPath = `${agreement}://${req.hostname}:${port}/videos_thumbnail/${newfilename}`;
		}
		let dirPath = `/videos/${filename}`;
		// 如果是视频文件，则处理封面
		let thumbnail = null;
		//保存在文件夹中的位置
		const thumbnailPath = path.join(rootDirname, 'public/videos_thumbnail',newfilename);
		ffmpeg(file.path)
			.format('webp') // 指定输入格式 
			.on('error', (err) => {
				obj_file.msg = err.message
				res.end(JSON.stringify(obj_file));
			})
			.on('end', () => {
				thumbnail = newThumbnailPath;
				obj_file = {
					...obj_file,
					code: 200,
					msg: "上传成功",
					...{
						originalname,
						filename,
						path: newFilePath,
						dirPath,
						mimetype,
						size,
						thumbnail
					}
				}
				res.end(JSON.stringify(obj_file));
			})
			.screenshot({
				timemarks: ["00:00:01"], // 指定截取的时间点，单位为秒, 设置为1秒，因为精确到0秒可能会因为编解码延迟而错过第一帧
				filename: path.basename(thumbnailPath), // 输出文件名
				folder: path.dirname(thumbnailPath), // 输出文件夹
				size: '1280x720' // 输出图片尺寸 1080x1920

			})

	} catch (e) {
		obj_file.msg = e.message
		res.end(JSON.stringify(obj_file));
	}
}

module.exports = upload_file_video;